import log from 'electron-log';
import axios from 'axios'
import fs from 'fs'
import path from 'path'
import { Parser } from 'm3u8-parser';
import { IncomingMessage } from 'http';

/**
 * 下载 m3u8 文件并保持文件到本地
 * @param url 下载文件地址
 * @param filePath 下载文件存储地址
 * @param name 下载文件名
 */
export async function downlodAndSaveM3U8(url: string, filePath: string, fileName: string) {
  // 获取存储目录
  const directory = path.dirname(filePath)

  // 判断是否存在路径
  if(!fs.existsSync(directory)) {
    fs.mkdirSync(directory)
  }

  log.info(`download m3u8 task url: ${url}`)

  try {
    // 下载文件
    const resp = await axios.get<string>(url, { method: "GET" })
    
    // 将 m3u8 中的 ts 路径去掉， 本地存储的时候不需要额外路径
    const parser = new Parser()
    parser.push(resp.data)
    parser.end()
    const uri = parser.manifest.segments[0].uri;
    const tsUriPath = uri.substring(0, uri.lastIndexOf('/'))
    const m3u8 = tsUriPath!== '' ? resp.data.replaceAll(tsUriPath, `/${fileName}`) : resp.data

    // console.log('m3u8 =', parser.manifest)

    // 将文件保存到系统 m3u8 文件保存路径
    // const myPath = path.resolve(filePath, 'index.m3u8')
    const writeResult = fs.writeFileSync(filePath, m3u8)

    log.info(`save m3u8 file [savePath]: ${filePath} [url]: ${url}`)

    return Promise.resolve(parser.manifest)

  } catch (error) {
    log.info(`download m3u8 task [error]: ${error} [url]: ${url}`)

    return Promise.resolve(undefined)
  }
  
}


/**
 * 下载 ts 文件并保持文件到本地
 * @param url 下载文件地址
 * @param filePath 下载文件存储地址
 * @param name 下载文件名
 */
 export async function downlodAndSaveTS(url: string, filePath: string) {
  // 获取存储目录
  const directory = path.dirname(filePath)
  // 判断是否存在路径
  if(!fs.existsSync(directory)) {
    fs.mkdirSync(directory)
  }

  // log.info(`download ts url: ${url}`)

  try {
    const writer = fs.createWriteStream(filePath)

    // 下载文件 IncomingMessage
    const resp = await axios.get<IncomingMessage>(url, { 
      method: "GET",
      responseType: 'stream' 
    })
    
    resp.data.pipe(writer)
    
    return new Promise((resolve, reject) => {
      writer.on('finish', () => {
        log.error(`download ts and write file done [file]: ${filePath} [url]: ${url}`)
        resolve({code: 0})
      })
      writer.on('error', (error) => {
        log.error(`download ts and write file [error]: ${error} [url]: ${url}`)
        resolve({code: 1})
      })
    })

  } catch (error: any) {
    // console.log('err =', error.message, error.code)
    log.error(`download ts file [error]: ${error} [url]: ${url}`)
    
    if(error.message.includes('632')) {
      return Promise.resolve({code: 632})
    }

    return Promise.resolve({code: 1})
  }
  
}